﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Infragistics.Controls.Interactions;
using Infragistics.Controls.Editors;
using System.Threading;
using Ivvy_Silverlight.i7SR;


namespace Ivvy_Silverlight.Ivvy
{
    public partial class Search : UserControl
    {
        private ObservableCollection<i_CalendarItem> CalendarItemsSearchResult;                    
        public Search()
        {
            InitializeComponent();
            CalendarItemsSearchResult = new ObservableCollection<i_CalendarItem>();
            DoSearch(GetDefaultDataManager());
            
            
           // PrepareControls(GetDefaultDataManager());
        }//public Search()

        private DataManipulations GetDefaultDataManager()
        {
            return MainPage.DataManager;
        }//private DataManipulations GetDefaultDataManager

        private void PrepareControls(DataManipulations DataManager)
        {
            CalendarItemsSearchResult = new ObservableCollection<i_CalendarItem>();
            List<SearchParam> FirstNameL = new List<SearchParam>();
            List<SearchParam> LastNameL = new List<SearchParam>();
            int FirstNameSelectedIndex = -1;
            int LastNameSelectedIndex = -1;

            foreach (var CurCalendarItem in DataManager.Data.CalendarItemsC)
            {
                if (CurCalendarItem.FirstName != null)
                {
                    bool ExistInList = false;
                    string FirstName = CurCalendarItem.FirstName.TrimEnd();
                    foreach (var CurrentFirstName in FirstNameL)
                        if (CurrentFirstName.Value == FirstName)
                        {
                            ExistInList = true;
                            break;
                        }
                    if (!ExistInList)
                    {
                        FirstNameL.Add(new SearchParam() { Value = FirstName });
                        if (FirstName == "Holly" && FirstNameSelectedIndex == -1)
                            FirstNameSelectedIndex = FirstNameL.Count - 1;
                    }
                }
                if (CurCalendarItem.LastName != null)
                {
                    bool ExistInList = false;
                    string LastName = CurCalendarItem.LastName.TrimEnd();
                    foreach (var CurrentLastName in LastNameL)
                        if (CurrentLastName.Value == LastName)
                        {
                            ExistInList = true;
                            break;
                        }
                    if (!ExistInList)
                    {
                        LastNameL.Add(new SearchParam() { Value = LastName });
                        if (LastName == "Robinson" && LastNameSelectedIndex == -1)
                            LastNameSelectedIndex = LastNameL.Count - 1;
                    }
                }//if (CurCalendarItem.LastName != null)
            }//foreach (var CurCalendarItem in DataManager.Data.CalendarItemsC)
            //FirstNameComboBox.ItemsSource = FirstNameL;
            //FirstNameComboBox.DisplayMemberPath = "Value";
            //if (FirstNameSelectedIndex != -1)
            //    FirstNameComboBox.SelectedIndex = FirstNameSelectedIndex;

            //LastNameComboBox.ItemsSource = LastNameL;
            //LastNameComboBox.DisplayMemberPath = "Value";
            //if (LastNameSelectedIndex != -1)
            //    LastNameComboBox.SelectedIndex = LastNameSelectedIndex;
            tbSearch.Focus();
        }//private void PrepareControls(DataManipulations DataManager)

        public static XamDialogWindow CreateParentDialogWindow(Search ChildSearchcontrol)
        {
            return new XamDialogWindow()
            {                
                Width = 800,
                Height = 560,
                Header = "Search",
                IsModal = false,
                StartupPosition = StartupPosition.Center,
                Content = ChildSearchcontrol
            };
        }//public static XamDialogWindow CreateParentDialogWindow()

        private void CloseButton_Click(object sender, RoutedEventArgs e)
        {
            SpecialClose();
        }//private void CloseButton_Click(object sender, RoutedEventArgs e)

        private void SpecialClose()
        {
            if (Parent is XamDialogWindow)
                ((XamDialogWindow)Parent).Close();
        }//private void SpecialClose()

        private void SearchButton_Click(object sender, RoutedEventArgs e)
        {            
            DoSearch(GetDefaultDataManager());
            
        }//private void SearchButton_Click(object sender, RoutedEventArgs e)

        private void DoSearch(DataManipulations DataManager)
        {
            CalendarItemsSearchResult.Clear();
            tbSearch.Text = "bo";
            //string FirstNameToSerach = tbSearch.Text.TrimEnd();
            //string LastNameToSerach = tbSearch.Text.TrimEnd();

            
            //string FirstNameToSerach = (FirstNameComboBox.SelectedItem as SearchParam).Value;
            //string LastNameToSerach = (LastNameComboBox.SelectedItem as SearchParam).Value;

            foreach (var CurCalendarItem in DataManager.Data.CalendarItemsC)
                if (CurCalendarItem.FirstName != null &&
                        CurCalendarItem.LastName != null)
                    if (CurCalendarItem.FirstName.TrimEnd().Contains(tbSearch.Text.TrimEnd())
                                        |CurCalendarItem.LastName.TrimEnd().Contains(tbSearch.Text.TrimEnd())
                        )
                        CalendarItemsSearchResult.Add(CurCalendarItem);
            ShowSearchResult();
            DoSearchCalendarItemOnServer(tbSearch.Text.TrimEnd(), tbSearch.Text.TrimEnd());            
        }//private void DoSearch()


        private void ShowSearchResult()
        {
            ObservableCollection<SearchResult> SearchResults = new ObservableCollection<SearchResult>();
            foreach(var CurCalendarItem in CalendarItemsSearchResult)
                SearchResults.Add(new SearchResult()
                {
                    Number = CurCalendarItem.CalendarItem_ID,
                    FirsrName = CurCalendarItem.FirstName.TrimEnd(),
                    LastName = CurCalendarItem.LastName.TrimEnd(),
                    StartDate = CurCalendarItem.Start_Date,
                    EndDate = CurCalendarItem.End_Date
                });

            if (SearchResults.Count > 0)
            {
                SearchResultsDG.AutoGenerateColumns = true;
                SearchResultsDG.ItemsSource = SearchResults;
                SearchResultsDG.Visibility = Visibility.Visible;
            }
            else
            {
                MessageBox.Show("No items found", "Please try other search params", MessageBoxButton.OK);
                SearchResultsDG.Visibility = Visibility.Collapsed;
                //FirstNameComboBox.Focus();
                tbSearch.Focus();
            }
        }//private void ShowSearchResult(ObservableCollection<CalendarItem> FindedCalendarItems)

        private void DoSearchCalendarItemOnServer(string FirstNameToSerach, string LastNameToSerach)
        {
            WebClient CalendarItems_webC = new WebClient();
            CalendarItems_webC.DownloadStringCompleted += new DownloadStringCompletedEventHandler(CalendarItems_DownloadStringCompleted);
            FirstNameToSerach = System.Windows.Browser.HttpUtility.UrlEncode(FirstNameToSerach);
            LastNameToSerach = System.Windows.Browser.HttpUtility.UrlEncode(LastNameToSerach);
            string Params = "FirstNameToSerach='" + FirstNameToSerach + "'&" + "LastNameToSerach='" + LastNameToSerach + "'";
            CalendarItems_webC.DownloadStringAsync(new Uri(GetDefaultDataManager().ODataServiceURL + "SearchCalendarItems_in_Binary_via_CustomFunction?"+Params));           

        }//private void DoSearchCalendarItemOnServer(FirstNameToSerach, LastNameToSerach)

        void CalendarItems_DownloadStringCompleted(object Sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                Thread ParseThread = new Thread(CalendarItems_ParseThread);
                ParseThread.Start(e.Result);                
            }//if (e.Error == null)
        }//void CalendarItems_DownloadStringCompleted(object Sender, DownloadStringCompletedEventArgs e)

        private void CalendarItems_ParseThread(object DoParseThreadParam)
        {
            ObservableCollection<i_CalendarItem> CalendarItemsFromServer = (ObservableCollection<i_CalendarItem>)SaveLoad.LoadFromBinary(DataManipulations.FromXMLCustomOData_toBinary(DoParseThreadParam as string));
            bool NeedRefresh = false;
            foreach (var CurCalendarItemFromServer in CalendarItemsFromServer)
            {
                bool AlreadyExist = false;
                foreach (var CurCalendarItemFromClient in CalendarItemsSearchResult)
                    if (CurCalendarItemFromClient.CalendarItem_ID == CurCalendarItemFromServer.CalendarItem_ID)
                    {
                        AlreadyExist = true;
                        break;
                    }
                if (!AlreadyExist)
                {
                    NeedRefresh = true;
                    CalendarItemsSearchResult.Add(CurCalendarItemFromServer);
                }
            }//foreach (var CurCalendarItemFromServer in CalendarItemsFromServer)
            if (NeedRefresh)
                Dispatcher.BeginInvoke(() =>
                {
                    ShowSearchResult();
                });
        }//private void CalendarItems_ParseThread(object DoParseThreadParam)



  }//public partial class Search : UserControl

    

    public class SearchResult
    {
        public SearchResult() { }
        public int Number  { get; set; }
        public string FirsrName  { get; set; }
        public string LastName { get; set; }
        public DateTime StartDate { get; set; }
        public DateTime EndDate { get; set; }
    }//public class SearchResult

    public class SearchParam
    {
        public SearchParam() { }        
        public string Value { get; set; }
    }//public class SearchParam

}//namespace Ivvy_Silverlight.Ivvy
